<template>
<section>
    <el-container>
        <el-main class="pad-no square-container" style="overflow: visible;">
            <section class="layout">
                <!-- <div class="layout"> -->
                    <div style="overflow: hidden;">
                        <ul v-for="(rowItem, rowIndex) in squareList" :key="rowIndex">
                            <li ref="cubes" v-for="(colItem, colIndex) in rowItem.list" :key="colIndex" :class="['custom-rubik-cube',hoverSquareList.includes(colItem.coordinates)?'selected':'']" :data-coordinates="colItem.coordinates" @click="chooseSquare(colItem,rowIndex,colIndex,beginPoint,endPoint)" @mousemove="moveSquare(colItem,rowIndex,colIndex,beginPoint)">
                                <div>+</div>
                            </li>
                        </ul>
                    </div>
                    <div ref="marker" v-if="config.markerModel == 'auto'" v-for="(finishItem, finishIndex) in finishSquareList" :key="finishIndex" :class="['selected-rubik-cube',current == finishIndex?'current':'']" v-bind:style="finishItem.style" @click="markerTigger(finishIndex)"><i v-if="current == finishIndex" class="el-icon-circle-close  " @click="deleteFinish(finishIndex)"></i>{{finishItem.text}}</div>
                    <div ref="marker" v-if="config.markerModel != 'auto'" v-for="(finishItem, finishIndex) in finishSquareList" :key="finishIndex" :class="['selected-rubik-cube',current == finishIndex?'current':'']" v-bind:style="finishItem.style" @click="markerTigger(finishIndex)">{{finishItem.style.text}}</div>
                <!-- </div> -->
            </section>
        </el-main>
    </el-container>
</section>
</template>

<script>
import {
  tooggleArray
} from '@/utils/index'
import defaultConfig from './utils/config'
export default {
  mixins: [defaultConfig.mixins],
  props: {
    defaultConfig: {
      type: Object,
      default: function() {
        return defaultConfig
      }
    },
    changeEvt: {
      type: Function,
      default: null,
      required: false
    }
  },
  data() {
    return {
      beginPoint: -1,
      endPoint: -1,
      current: 0,
      hoverSquareList: [], // 存放hover的魔方块
      finishSquareList: [], // 存放选中过得的魔方块
      chooseSquareList: [], // 二维数组，存放保存的符合条件的魔方块
      squareList: [{
        name: 'row1',
        list: [{
          coordinates: '1:1'
        },
        {
          coordinates: '1:2'
        },
        {
          coordinates: '1:3'
        },
        {
          coordinates: '1:4'
        }
        ]
      },
      {
        name: 'row2',
        list: [{
          coordinates: '2:1'
        },
        {
          coordinates: '2:2'
        },
        {
          coordinates: '2:3'
        },
        {
          coordinates: '2:4'
        }
        ]
      },
      {
        name: 'row3',
        list: [{
          coordinates: '3:1'
        },
        {
          coordinates: '3:2'
        },
        {
          coordinates: '3:3'
        },
        {
          coordinates: '3:4'
        }
        ]
      },
      {
        name: 'row4',
        list: [{
          coordinates: '4:1'
        },
        {
          coordinates: '4:2'
        },
        {
          coordinates: '4:3'
        },
        {
          coordinates: '4:4'
        }
        ]
      }
      ]
    }
  },
  watch: {
    'config.initList': {
      handler(newData, oldData) {
        if (Array.isArray(newData) && newData.length > 0) {
          this.$nextTick(() => {
            const [{ hoverSquareList = [], finishSquareList = [], chooseSquareList = [] }] = newData
            this.hoverSquareList = hoverSquareList
            this.finishSquareList = finishSquareList
            this.chooseSquareList = chooseSquareList
          })
        }
      },
      immediate: true,
      deep: false
    }
  },
  mounted() {
    this.markerW = this.$refs.cubes[0].offsetWidth
    this.markerH = this.$refs.cubes[0].offsetHeight
  },
  methods: {
    reset() {
      // 重置数据
      this.hoverSquareList = []
      this.finishSquareList = []
      this.chooseSquareList = []
    },
    moveSquare(colItem, row, col, begin) {
      const coordinates = colItem.coordinates
      if (begin !== -1) {
        const [beginStart, endStart, beginOver, endOver] = this.revisePoint(begin, coordinates)
        const countCover = this.countCover(beginStart, endStart, beginOver, endOver)
        if (!this.hasCover(countCover)) {
          // 如果满足存入条件,则添加进入显示hover状态
          this.$nextTick(() => {
            this.hoverSquareList = [...countCover]
          })
        }
      }
    },
    markerTigger(markerIndex) {
      this.current = markerIndex
      this.output()
    },
    deleteFinish(markerIndex) {
      this.finishSquareList.splice(markerIndex, 1)
      this.chooseSquareList.splice(markerIndex, 1)
      this.$nextTick(() => {
        this.current = this.finishSquareList.length - 1
      })
      this.hoverSquareList = []
    },
    chooseSquare(colItem, row, col, begin, end) {
      if (begin === -1) {
        // 点击起点
        this.beginPoint = colItem.coordinates
        tooggleArray(this.hoverSquareList, colItem.coordinates)
      } else if (end === -1) {
        // 点击终点
        this.endPoint = colItem.coordinates

        const begin = this.beginPoint
        const end = this.endPoint
        const [beginStart, endStart, beginOver, endOver] = this.revisePoint(begin, end)
        const countCover = this.countCover(beginStart, endStart, beginOver, endOver)
        if (!this.hasCover(countCover)) {
          // 如果满足存入条件，则放入chooseSquareList
          // console.log(countCover);
          this.chooseSquareList.push(countCover)
          this.createMarker(beginStart, endStart, beginOver, endOver)
        } else {
          this.hoverSquareList = []
        }
        this.clearPoint()
      }
    },
    revisePoint(begin, end) {
      let [beginStart, beginOver] = begin.split(':')
      let [endStart, endOver] = end.split(':')

      // 如果开始行大于结束行，则开始行用结束行，结束行用开始行
      if (beginStart > endStart) {
        [endStart, beginStart] = [beginStart, endStart]
      }

      // 如果开始列大于结束列，则开始列用结束列，结束列用开始列
      if (beginOver > endOver) {
        [endOver, beginOver] = [beginOver, endOver]
      }

      return [beginStart, endStart, beginOver, endOver]
    },
    countCover(beginStart, endStart, beginOver, endOver) {
      const saveScopeList = [] // 存储当前选中的区块

      // 获取起点及其终点坐标的起始数值
      this.squareList.map((rowItem, rowIndex) => {
        const colLits = rowItem.list
        colLits.map((colItem, colIndex) => {
          const [colbegin, colend] = colItem.coordinates.split(':')
          const _thisPoint = `${colbegin}:${colend}`
          // 遍历每一行列魔方块，判断符合筛选条件的区域
          if ((colbegin >= beginStart && colend >= beginOver) && (colbegin <= endStart && colend <= endOver)) {
            saveScopeList.push(_thisPoint)
          }
        })
      })
      return saveScopeList
    },
    hasCover(countCover) {
      // 根据筛选出来的符合条件的区域块，和存储起来的已有的区块进行对比判断是否有覆盖范围
      let isCover = false
      if (this.chooseSquareList.length > 0) {
        isCover = this.chooseSquareList.some((squareItem, squareIndex) => {
          const isCover = squareItem.some((pointItem, pointIndex) => {
            return countCover.includes(pointItem)
          })
          return isCover
        })
      }
      return isCover
    },
    createMarker(beginStart, endStart, beginOver, endOver) {
      const params = {
        style: {
          'top': 0,
          'left': 0,
          'width': 0,
          'height': 0,
          'padding-top': 0,
          'box-sizing': 'border-box'
        },
        text: '',
        data: {
          beginStart: beginStart,
          beginOver: beginOver,
          endStart: endStart,
          endOver: endOver,
          thumb: {
            file_path: 'default_banner.png'
          },
          link: ''
        }
      }
      // console.log(beginStart,endStart,beginOver,endOver);
      // 根据区域块的位置，生成覆盖物
      const markerW = this.markerW / 4
      const markerH = this.markerH / 4

      params.style.top = `${markerH * 4 * (beginStart - 1)}px`
      params.style.left = `${markerW * 4 * (beginOver - 1)}px`// 计算偏移值
      params.style.width = markerW * 4 * (endOver - beginOver + 1)// 计算偏移值
      params.style.height = markerH * 4 * (endStart - beginStart + 1)// 计算偏移值
      params.style['padding-top'] = `${(params.style.height - 20) / 2}px`// 计算文字居中位置
      params.text = `${params.style.width}x${params.style.height}`// 计算文字内容
      params.style.width = `${params.style.width}px`// 添加单位
      params.style.height = `${params.style.height}px`// 添加单位
      this.finishSquareList.push(params)
      this.$nextTick(() => {
        this.current = this.finishSquareList.length - 1
        this.output()
      })
    },
    clearPoint() {
      this.beginPoint = this.endPoint = -1
    },
    output(saveMagicSquare) {
      if (
        Object.prototype.toString.call(this.changeEvt) === '[object Function]'
      ) {
        this.changeEvt({ hoverSquareList: this.hoverSquareList, finishSquareList: this.finishSquareList, chooseSquareList: this.chooseSquareList, current: this.current })
      }
    },
    destroyed() {
      this.reset()
    }
  }
}
</script>

<style lang="scss" scoped>
.square-container {
    .layout {
        clear: both;
        position: relative;
        width: 280px;
    }

    .layout ul {
        overflow: hidden;
        list-style: none;
        padding: 0;
    }

    .layout li {
        float: left;
        background: #EBF8FD;
        color: #88c4dc;
        border: 1px solid #bdf;
        cursor: pointer;
        font-size: 12px;
        box-sizing: border-box;
    }

    .layout li div {
        text-align: center;
    }

    .layout p {
        margin-top: 10px;
        color: #999;
        font-size: 12px;
        float: right;
    }

    /*自定义魔方*/
    .layout li.custom-rubik-cube {
        width: 25%;
        height: 70px;
        border: 1px solid #e5e5e5;
        border-left: 0;
        border-bottom: 0;
        background: #f8f8f8;
    }

    .layout li.custom-rubik-cube:nth-child(4n+1) {
        border-left: 1px solid #e5e5e5;
    }

    .layout ul:last-child li {
        border-bottom: 1px solid #e5e5e5;
    }

    .layout li.custom-rubik-cube>div {
        padding-top: 23px;
        font-size: 20px;
        color: #bbb;
    }

    .layout li.custom-rubik-cube.selected {
        background: #EBF8FD;
    }

    .layout li.custom-rubik-cube.selected>div {
        display: none;
    }

    .layout div.selected-rubik-cube {
        position: absolute;
        cursor: pointer;
        border: 1px solid #cbe3ec;
        background: #e8f7fd;
        text-align: center;
        color: #88c4dc;
        font-size: 12px;
    }

    .layout div.selected-rubik-cube.current {
        border: 1px solid #38f;
        .el-icon-circle-close  {
            display:none;
        }
        &:hover .el-icon-circle-close  {
            position: absolute;
            display:block;
            cursor: pointer;
            top: -11px;
            right: -11px;
            font-size: 21px;
            color: rgb(187,187,187);
            z-index: 2;
        }
    }
}
</style>
